<template>
  <view class="addpets">
    <view class="box1" @click="back">
      <uv-icon name="arrow-left" color="#fff"></uv-icon>
      <view class="box11">添加宠物</view>
    </view>
    <view class="addpets-form">
      <view class="form">
        <uv-form labelPosition="left" :model="model1" :rules="rules" ref="form">
          <uv-form-item borderBottom prop="userInfo.name">
            宠物名字
            <uv-input v-model="model1.userInfo.name" border="none" placeholder="请输入宠物名字" inputAlign="right">
            </uv-input>
          </uv-form-item>
          <uv-form-item label="类型" v-model="model1.userInfo.type" prop="userInfo.type" borderBottom
            @click="showtypeSelect">
            <uv-input v-model="model1.userInfo.type" disabled disabledColor="#ffffff" placeholder="请选择类型" border="none"
              inputAlign="right">
            </uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item borderBottom prop="userInfo.age">
            年龄
            <uv-input border="none" v-model="model1.userInfo.age" placeholder="请输入宠物年龄" inputAlign="right">
            </uv-input>
          </uv-form-item>
          <uv-form-item borderBottom>
            性别<uv-radio-group v-model="sex">
              <uv-radio :customStyle="{ margin: '8px' }" v-for="(item, index) in radiolist" :key="index"
                :label="item.name" :name="item.name">
              </uv-radio>
            </uv-radio-group>
          </uv-form-item>
          <uv-form-item> 主人描述 </uv-form-item>
          <uv-form-item borderBottom>
            <uv-textarea v-model="textara" placeholder="请输入内容"></uv-textarea>
          </uv-form-item>
          <uv-form-item> 宠物图片 </uv-form-item>
          <uv-form-item borderBottom>
            <uv-upload :fileList="fileList1" name="1" multiple :maxCount="10" @afterRead="afterRead"
              @delete="deletePic"></uv-upload>
          </uv-form-item>
          <uv-button type="primary" text="保存" color="#008c8c" shape="circle" customStyle="margin-top: 10px"
            @click="submit"></uv-button>
        </uv-form>
        <uv-action-sheet ref="typeSelect" :actions="actions" title="请选择类型" @select="typeSelect">
        </uv-action-sheet>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    uniRequest
  } from "../../utils/request.js"
  export default {
    data() {
      return {
        fileList1: [],
        textara: "",
        sex: "女生",
        radiolist: [{
            name: "女生",
            disabled: false,
          },
          {
            name: "男生",
            disabled: false,
          },
        ],
        model1: {
          userInfo: {
            name: "",
            type: "",
            age: "",
          },
        },
        actions: [{
            name: "猫猫",
          },
          {
            name: "狗狗",
          },
          {
            name: "卡皮巴拉",
          },
        ],
        rules: {
          "userInfo.name": {
            type: "string",
            required: true,
            message: "请填写姓名",
            trigger: ["blur", "change"],
          },
          "userInfo.type": {
            type: "string",
            required: true,
            message: "请选择类型",
            trigger: ["blur", "change"],
          },
          "userInfo.age": {
            type: "string",
            required: true,
            message: "请填写年龄",
            trigger: ["blur", "change"],
          },
        },
        radio: "",
        switchVal: false,
      };
    },
    methods: {
      // 提交
      back() {
        uni.navigateBack({
          delta: 1, // 返回1个，如果是2，返回2个页面
        });
      },
      submit() {
        // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
        this.$refs.form
          .validate()
          .then((res) => {
            uni.showToast({
              icon: "success",
              title: "校验通过",
            });
          })
          .catch((errors) => {
            uni.showToast({
              icon: "error",
              title: "校验失败",
            });
          });
        const id = Math.ceil(Math.random() * 100);
        const name = this.model1.userInfo.name
        const type = this.model1.userInfo.type
        const sex = this.sex
        const age = this.model1.userInfo.age
        const description = this.textara
        console.log(name, type, sex, age, description)
        uniRequest('pet/add?server=1', function(err, data) {
          if (err) {
            // 错误
            console.log(err)
          } else {
            console.log('"成功了"', data)
          }
        }, 'POST', {
          master_id: id,
          name: name,
          type: type,
          sex: sex,
          age: age,
          description: description,
          image: '#'
        });
      },
      // 类型选择
      showtypeSelect() {
        this.$refs.typeSelect.open();
        this.hideKeyboard();
      },
      // 类型选择返回结果
      typeSelect(e) {
        this.model1.userInfo.type = e.name;
        // 对部分表单字段进行校验
        this.$refs.form.validateField("userInfo.type", (err) => {
          // 处理错误后的逻辑
        });
      },
      hideKeyboard() {
        uni.hideKeyboard();
      },
      // 删除图片
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
      },
      // 新增图片
      async afterRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file)
        let fileListLen = this[`fileList${event.name}`].length
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          let item = this[`fileList${event.name}`][fileListLen]
          this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: result
          }))
          fileListLen++
        }
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
            filePath: url,
            name: 'file',
            formData: {
              user: 'test'
            },
            success: (res) => {
              setTimeout(() => {
                resolve(res.data.data)
              }, 1000)
            }
          });
        })
      }
    },
  };
</script>

<style lang="scss">
  @import url("tianjiacw.scss");
</style>